package com.sophie.service.impl;

import com.sophie.dao.IUserDAO;
import com.sophie.dao.impl.UserDAOImpl;
import com.sophie.entity.User;
import com.sophie.service.IUserService;
import com.sophie.util.ResultVO;

import java.sql.SQLException;
import java.util.List;

/**
 * @Author: Rowena
 * @CreateTime: 2024-08-30 08:42:37
 * @Version: 1.0
 */

public class UserServiceImpl implements IUserService {
    IUserDAO userDAO = new UserDAOImpl();
    @Override
    public ResultVO register(User user) {
        try {
            if (user == null) {
                return ResultVO.fail("用户注册失败！");
            }
            int register = userDAO.register(user);
            if (register > 0) {
                return ResultVO.ok("用户注册成功！");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return ResultVO.fail("用户注册失败！");
    }

    @Override
    public ResultVO login(String username, String password) {
        try {
            User user = userDAO.login(username, password);
            if (user != null) {
                return ResultVO.ok("用户登录成功！").setData(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return ResultVO.fail("用户登录失败！");
    }

    @Override
    public ResultVO checkUserName(String username) {
        try {
            long count = userDAO.checkUserName(username);
            if (count==0){
                return ResultVO.ok("此用户名可用！");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return ResultVO.fail("此用户名已被注册");
    }

    @Override
    public ResultVO getUserList() {
        try {
            List<User> userList = userDAO.getUserList();
            if(!userList.isEmpty()){
                return ResultVO.ok("用户列表成功获取").setData(userList);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        return ResultVO.fail("用户列表获取失败！");
    }

    @Override
    public ResultVO getUserById(int id) {
        try {
            User user = userDAO.getUserById(id);
            if (user != null) {
                return ResultVO.ok("用户信息获取成功").setData(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return ResultVO.fail("用户信息获取失败");
    }

    @Override
    public ResultVO updateUser(User user) {
        try {
            int i = userDAO.updateUser(user);
            if (i > 0) {
                return ResultVO.ok("用户信息更新成功!");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return ResultVO.fail("用户信息更新失败");
    }
}
